package com.wsoft.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.constant.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.annotation.InitRedisCache;
import com.wsoft.core.exception.Asserts;
import com.wsoft.system.dto.SysMenuNode;
import com.wsoft.system.entity.*;
import com.wsoft.system.mapper.SysMemberMapper;
import com.wsoft.system.query.member.MemberInsertQuery;
import com.wsoft.system.query.member.MemberListQuery;
import com.wsoft.system.query.member.MemberUpdateQuery;
import com.wsoft.system.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工表 服务实现类
 * </p>
 *
 * @author juiet
 * @since 2024年09月03日 10:35:18
 */
@Service
public class SysMemberServiceImpl extends ServiceImpl<SysMemberMapper, SysMemberEntity> implements ISysMemberService {

    @Resource
    private ISysMemberOrgRoleRelationService memberOrgRoleRelationService;

    @Resource
    private ISysRoleMenuRelationService roleMenuRelationService;
    @Resource
    private ISysMemberOrgPostRelationService memberOrgPostRelationService;


    @Resource
    private ISysAccountService accountService;

    @Resource
    private ISysMenuService menuService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(MemberInsertQuery query) {
        //todo 唯一性校验
        SysMemberEntity convert = Convert.convert(SysMemberEntity.class, query);
        boolean b = save(convert);
        if (b){
            //新增人员组织关系
            if (convert.getCurOrgId()!=null){
                SysMemberOrgRoleRelationEntity orgRelation = new SysMemberOrgRoleRelationEntity();
                orgRelation.setMemberId(convert.getId());
                orgRelation.setOrgId(query.getCurOrgId());
                memberOrgRoleRelationService.save(orgRelation);
            }
            //新增人员岗位关系
            if (convert.getCurPostId()!=null){
                SysMemberOrgPostRelationEntity postRelation = new SysMemberOrgPostRelationEntity();
                postRelation.setMemberId(convert.getId());
                postRelation.setOrgId(query.getCurOrgId());
                postRelation.setPostId(query.getCurPostId());
                memberOrgPostRelationService.save(postRelation);
            }
            //初始化账号
            QueryWrapper<SysAccountEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SysAccountEntity::getLoginName,query.getLoginName());
            if (accountService.count(queryWrapper)>0){
                Asserts.fail("[sys.account.exist]");
            }
            SysAccountEntity entity = new SysAccountEntity();
            entity.setMemberId(convert.getId());
            entity.setLoginName(query.getLoginName());
            entity.setLoginPw("207cf410532f92a47dee245ce9b11ff71f578ebd763eb3bbea44ebd043d018fb");
            entity.setConfigLayout("default");
            entity.setConfigSkin("windows4");
            entity.setConfigLocation("left");
            entity.setIsUsed(1);
            accountService.save(entity);
        }
        return b;
    }

    @Override
    @InitRedisCache(types = {RedisKeyConstant.MEMBER_CACHE, RedisKeyConstant.MEMBER_ROLE_CACHE, RedisKeyConstant.MEMBER_POST_CACHE},
            values = {"id","id","id"})
    public boolean update(MemberUpdateQuery query) {
        SysMemberEntity convert = Convert.convert(SysMemberEntity.class, query);
        //原数据
        SysMemberEntity entity = getById(query.getId());
        boolean b = updateById(convert);
        if (b){
            //修改人员组织关系
            if(!query.getCurOrgId().equals(entity.getCurOrgId())){
                QueryWrapper<SysMemberOrgRoleRelationEntity> orgQuery =  new QueryWrapper<>();
                orgQuery.lambda().eq(SysMemberOrgRoleRelationEntity::getMemberId,convert.getId());
                List<SysMemberOrgRoleRelationEntity> list = memberOrgRoleRelationService.list(orgQuery);
                List<Long> orgList = list.stream().map(SysMemberOrgRoleRelationEntity::getOrgId).collect(Collectors.toList());
                if (!orgList.contains(convert.getCurOrgId())){
                    SysMemberOrgRoleRelationEntity orgRelation = new SysMemberOrgRoleRelationEntity();
                    orgRelation.setMemberId(convert.getId());
                    orgRelation.setOrgId(convert.getCurOrgId());
                    memberOrgRoleRelationService.save(orgRelation);
                }
            }
            //修改人员组织岗位关系
            if(!query.getCurPostId().equals(entity.getCurPostId())){
                QueryWrapper<SysMemberOrgPostRelationEntity> postQuery =  new QueryWrapper<>();
                postQuery.lambda().eq(SysMemberOrgPostRelationEntity::getMemberId,convert.getId());
                List<SysMemberOrgPostRelationEntity> list = memberOrgPostRelationService.list(postQuery);
                List<Long> postList = list.stream().map(SysMemberOrgPostRelationEntity::getPostId).collect(Collectors.toList());
                if (!postList.contains(convert.getCurPostId())){
                    SysMemberOrgPostRelationEntity postRelation = new SysMemberOrgPostRelationEntity();
                    postRelation.setMemberId(convert.getId());
                    postRelation.setOrgId(query.getCurOrgId());
                    postRelation.setPostId(query.getCurPostId());
                    memberOrgPostRelationService.save(postRelation);
                }
            }
        }
        return b;
    }

    @Override
    @GetRedisCache(type = RedisKeyConstant.MEMBER_CACHE,
                   value = RedisKeyConstant.REDIS_SELF)
    public SysMemberEntity getMember(Long id) {
        return getById(id);
    }

    @Override
    @InitRedisCache(types = {RedisKeyConstant.MEMBER_CACHE, RedisKeyConstant.MEMBER_ROLE_CACHE, RedisKeyConstant.MEMBER_POST_CACHE},
            values = {RedisKeyConstant.REDIS_SELF,RedisKeyConstant.REDIS_SELF,RedisKeyConstant.REDIS_SELF})
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public PageInfo<SysMemberEntity> pageList(MemberListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        QueryWrapper<SysMemberEntity> memberQuery = new QueryWrapper<>();
        //编号
        if (StrUtil.isNotBlank(query.getCode())) {
            memberQuery.lambda().eq(SysMemberEntity::getCode,query.getCode());
        }
        //姓名
        if (StrUtil.isNotBlank(query.getName())) {
            memberQuery.lambda().like(SysMemberEntity::getName,query.getName());
        }
        //手机号
        if (query.getPhone()!=null) {
            memberQuery.lambda().eq(SysMemberEntity::getPhone,query.getPhone());
        }
        //手机号
        if (query.getLoginOrgId()!=null) {
            memberQuery.lambda().eq(SysMemberEntity::getLoginOrgId,query.getLoginOrgId());
        }
            return  PageInfo.of(list(memberQuery));
        }

    @Override
    public List<SysMenuNode> treeMenuListByMemberId(Long memberId) {
        List<SysRoleEntity> roleList = memberOrgRoleRelationService.getRoleListByMember(memberId);
        List<SysMenuEntity> menuList = new ArrayList<>();
        roleList.forEach(e->{
            List<SysMenuEntity> list = roleMenuRelationService.getMenuListByRoleId(e.getId());
            menuList.addAll(list);
        });
        return menuService.treeList(menuList);
    }

}
